var express = require('express');
var router = express.Router();

// 引入第二种加密方式
const bcrypt = require('bcrypt');
// 引入生成token工具
const jwt = require('jsonwebtoken');
// 引入常量密钥
const { TOKEN_KEY } = require('../utils/const');

const { superLogin, addNewAdmin, getAdmins, updataAdminPassword, getAdminsId, frozenAdmin, isAdmins } = require('../service/adminsService');

// 管理员登录
router.post('/superLogin', async function (req, res, next) {
    // 接收前端发送过来的数据
    const { account, password } = req.body;
    const { data } = await superLogin({ account });
    if (data == undefined) {
        // 账号验证失败进入if
        res.send({
            message: '登陆失败',
            status: 0
        });
    } else {
        // bcrypt 运用conpareSync进行比较，为true代表密码正确  第二种加密方法
        const isLogin = bcrypt.compareSync(password, data.password);
        if (isLogin) {
            const token = jwt.sign(
                { account },//要保存的用户信息
                TOKEN_KEY,//秘钥字符串
                { expiresIn: "1h" },// 设置 token 的有效期 ，单位 s
            );
            res.send({
                message: '登陆成功',
                status: 1,
                token,
            });//把值响应前端
        } else {
            res.send({
                message: '登陆失败',
                status: 0
            });
        }
    }
});

// 增加管理员
router.post('/addNewAdmin', async function (req, res, next) {
    const { account, password } = req.body;
    // bcrypt  加密的方法hashasync
    const newpassword = bcrypt.hashSync(password, 10);
    const result = await addNewAdmin({ account, password: newpassword });
    res.send(result);
});

// 注册判断
router.post('/isAdmins', async function (req, res, next) {
    const item = req.body;
    const result = await isAdmins(item);
    res.send(result);
});

// 验证是否登录
router.get('/isLogin', async (req, res) => {
    // 1. 获取token
    const headerstoken = req.get('Authorization');
    const token = headerstoken.split(' ')[1];
    // 2.解码token，拿到用户信息
    const { account } = jwt.verify(token, TOKEN_KEY);
    res.send({
        message: '身份认证通过',
        status: 1,
        data: account,
    })
})

// 获取管理员信息
router.post('/getAdmins', async function (req, res, next) {
    const data = await getAdmins(req.body)
    res.send(data);
});

// 获取修改的_id
router.post('/getAdminsId', async function (req, res, next) {
    const data = await getAdminsId(req.body)
    res.send(data);
});

// 超级管理员修改密码
router.post('/updataAdminPassword', async function (req, res, next) {
    const { password, _id } = req.body;
    const newpassword = bcrypt.hashSync(password, 10);
    const { data } = await updataAdminPassword({ password: newpassword, _id })
    res.send(data);
});

// 禁用管理员
router.post('/frozenAdmin', async function (req, res, next) {
    const data = req.body;
    const result = await frozenAdmin(data)
    res.send(result);
});


module.exports = router;
